<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox, ElLink } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { loginApi, getInfo } from '@/api/login'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { Icon } from '@/components/Icon'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'

const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()

const rules = {
  username: [required()],
  password: [required()]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold text-center w-[100%]">{t('login.login')}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: 'admin or test'
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '123456',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: 'admin or test',
      // 按下enter键触发登录
      onKeydown: (_e: any) => {
        if (_e.key === 'Enter') {
          _e.stopPropagation() // 阻止事件冒泡
          signIn()
        }
      }
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('login.remember')} size="small" />
                <ElLink type="primary" underline={false}>
                  {t('login.forgetPassword')}
                </ElLink>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
              <div class="w-[100%] mt-15px">
                <BaseButton class="w-[100%]" onClick={toRegister}>
                  {t('login.register')}
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'other',
    component: 'Divider',
    label: t('login.otherLogin'),
    componentProps: {
      contentPosition: 'center'
    }
  },
  {
    field: 'otherIcon',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between w-[100%]">
                <Icon
                  icon="vi-ant-design:github-filled"
                  size={iconSize}
                  class="cursor-pointer ant-icon"
                  color={iconColor}
                  hoverColor={hoverColor}
                />
                <Icon
                  icon="vi-ant-design:wechat-filled"
                  size={iconSize}
                  class="cursor-pointer ant-icon"
                  color={iconColor}
                  hoverColor={hoverColor}
                />
                <Icon
                  icon="vi-ant-design:alipay-circle-filled"
                  size={iconSize}
                  color={iconColor}
                  hoverColor={hoverColor}
                  class="cursor-pointer ant-icon"
                />
                <Icon
                  icon="vi-ant-design:weibo-circle-filled"
                  size={iconSize}
                  color={iconColor}
                  hoverColor={hoverColor}
                  class="cursor-pointer ant-icon"
                />
              </div>
            </>
          )
        }
      }
    }
  }
])

const iconSize = 30

const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
onMounted(() => {
  initLoginInfo()
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)

const iconColor = '#999'

const hoverColor = 'var(--el-color-primary)'

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserType>()

      try {
        const res = await loginApi(formData)
        console.log(res)
        userStore.setToken(res.data)

        const infoRes = await getInfo()
        console.log(infoRes.data)

        if (res) {
          // 是否记住我
          if (unref(remember)) {
            userStore.setLoginInfo({
              username: formData.username,
              password: formData.password
            })
          } else {
            userStore.setLoginInfo(undefined)
          }
          userStore.setRememberMe(unref(remember))
          // userStore.setUserInfo(res.data)
          userStore.setUserInfo(infoRes.data.user)
          // 是否使用动态路由
          if (appStore.getDynamicRouter) {
            // getRole()
            const routers: AppCustomRouteRecordRaw[] = [
              {
                path: '/dashboard',
                component: '#',
                redirect: '/dashboard/analysis',
                name: 'Dashboard',
                meta: {
                  title: 'router.dashboard',
                  icon: 'vi-ant-design:dashboard-filled',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'analysis',
                    component: 'views/Dashboard/Analysis',
                    name: 'Analysis',
                    meta: {
                      title: 'router.analysis',
                      noCache: true,
                      affix: true
                    }
                  },
                  {
                    path: 'workplace',
                    component: 'views/Dashboard/Workplace',
                    name: 'Workplace',
                    meta: {
                      title: 'router.workplace',
                      noCache: true,
                      affix: true
                    }
                  }
                ]
              },
              {
                path: '/external-link',
                component: '#',
                meta: {},
                name: 'ExternalLink',
                children: [
                  {
                    path: 'https://element-plus-admin-doc.cn/',
                    name: 'DocumentLink',
                    component: '',
                    meta: {
                      title: 'router.document',
                      icon: 'vi-clarity:document-solid'
                    }
                  }
                ]
              },
              {
                path: '/guide',
                component: '#',
                name: 'Guide',
                meta: {},
                children: [
                  {
                    path: 'index',
                    component: 'views/Guide/Guide',
                    name: 'GuideDemo',
                    meta: {
                      title: 'router.guide',
                      icon: 'vi-cib:telegram-plane'
                    }
                  }
                ]
              },
              {
                path: '/components',
                component: '#',
                redirect: '/components/form/default-form',
                name: 'ComponentsDemo',
                meta: {
                  title: 'router.component',
                  icon: 'vi-bx:bxs-component',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'form',
                    component: '##',
                    name: 'Form',
                    meta: {
                      title: 'router.form',
                      alwaysShow: true
                    },
                    children: [
                      {
                        path: 'default-form',
                        component: 'views/Components/Form/DefaultForm',
                        name: 'DefaultForm',
                        meta: {
                          title: 'router.defaultForm'
                        }
                      },
                      {
                        path: 'use-form',
                        component: 'views/Components/Form/UseFormDemo',
                        name: 'UseForm',
                        meta: {
                          title: 'UseForm'
                        }
                      }
                    ]
                  },
                  {
                    path: 'table',
                    component: '##',
                    redirect: '/components/table/default-table',
                    name: 'TableDemo',
                    meta: {
                      title: 'router.table',
                      alwaysShow: true
                    },
                    children: [
                      {
                        path: 'default-table',
                        component: 'views/Components/Table/DefaultTable',
                        name: 'DefaultTable',
                        meta: {
                          title: 'router.defaultTable'
                        }
                      },
                      {
                        path: 'use-table',
                        component: 'views/Components/Table/UseTableDemo',
                        name: 'UseTable',
                        meta: {
                          title: 'UseTable'
                        }
                      },
                      {
                        path: 'tree-table',
                        component: 'views/Components/Table/TreeTable',
                        name: 'TreeTable',
                        meta: {
                          title: 'TreeTable'
                        }
                      },
                      {
                        path: 'table-image-preview',
                        component: 'views/Components/Table/TableImagePreview',
                        name: 'TableImagePreview',
                        meta: {
                          title: 'router.PicturePreview'
                        }
                      },
                      {
                        path: 'table-video-preview',
                        component: 'views/Components/Table/TableVideoPreview',
                        name: 'TableVideoPreview',
                        meta: {
                          title: 'router.tableVideoPreview'
                        }
                      },
                      {
                        path: 'card-table',
                        component: 'views/Components/Table/CardTable',
                        name: 'CardTable',
                        meta: {
                          title: 'router.cardTable'
                        }
                      }
                      // {
                      //   path: 'ref-table',
                      //   component: 'views/Components/Table/RefTable',
                      //   name: 'RefTable',
                      //   meta: {
                      //     title: 'RefTable'
                      //   }
                      // }
                    ]
                  },
                  {
                    path: 'editor-demo',
                    component: '##',
                    redirect: '/components/editor-demo/editor',
                    name: 'EditorDemo',
                    meta: {
                      title: 'router.editor',
                      alwaysShow: true
                    },
                    children: [
                      {
                        path: 'editor',
                        component: 'views/Components/Editor/Editor',
                        name: 'Editor',
                        meta: {
                          title: 'router.richText'
                        }
                      },
                      {
                        path: 'json-editor',
                        component: 'views/Components/Editor/JsonEditor',
                        name: 'JsonEditor',
                        meta: {
                          title: 'router.jsonEditor'
                        }
                      },
                      {
                        path: 'code-editor',
                        component: 'views/Components/Editor/CodeEditor',
                        name: 'CodeEditor',
                        meta: {
                          title: 'router.codeEditor'
                        }
                      }
                    ]
                  },
                  {
                    path: 'search',
                    component: 'views/Components/Search',
                    name: 'Search',
                    meta: {
                      title: 'router.search'
                    }
                  },
                  {
                    path: 'descriptions',
                    component: 'views/Components/Descriptions',
                    name: 'Descriptions',
                    meta: {
                      title: 'router.descriptions'
                    }
                  },
                  {
                    path: 'image-viewer',
                    component: 'views/Components/ImageViewer',
                    name: 'ImageViewer',
                    meta: {
                      title: 'router.imageViewer'
                    }
                  },
                  {
                    path: 'dialog',
                    component: 'views/Components/Dialog',
                    name: 'Dialog',
                    meta: {
                      title: 'router.dialog'
                    }
                  },
                  {
                    path: 'icon',
                    component: 'views/Components/Icon',
                    name: 'Icon',
                    meta: {
                      title: 'router.icon'
                    }
                  },
                  {
                    path: 'icon-picker',
                    component: 'views/Components/IconPicker',
                    name: 'IconPicker',
                    meta: {
                      title: 'router.iconPicker'
                    }
                  },
                  {
                    path: 'echart',
                    component: 'views/Components/Echart',
                    name: 'Echart',
                    meta: {
                      title: 'router.echart'
                    }
                  },
                  {
                    path: 'count-to',
                    component: 'views/Components/CountTo',
                    name: 'CountTo',
                    meta: {
                      title: 'router.countTo'
                    }
                  },
                  {
                    path: 'qrcode',
                    component: 'views/Components/Qrcode',
                    name: 'Qrcode',
                    meta: {
                      title: 'router.qrcode'
                    }
                  },
                  {
                    path: 'highlight',
                    component: 'views/Components/Highlight',
                    name: 'Highlight',
                    meta: {
                      title: 'router.highlight'
                    }
                  },
                  {
                    path: 'infotip',
                    component: 'views/Components/Infotip',
                    name: 'Infotip',
                    meta: {
                      title: 'router.infotip'
                    }
                  },
                  {
                    path: 'input-password',
                    component: 'views/Components/InputPassword',
                    name: 'InputPassword',
                    meta: {
                      title: 'router.inputPassword'
                    }
                  },
                  {
                    path: 'waterfall',
                    component: 'views/Components/Waterfall',
                    name: 'Waterfall',
                    meta: {
                      title: 'router.waterfall'
                    }
                  },
                  {
                    path: 'image-cropping',
                    component: 'views/Components/ImageCropping',
                    name: 'ImageCropping',
                    meta: {
                      title: 'router.imageCropping'
                    }
                  },
                  {
                    path: 'video-player',
                    component: 'views/Components/VideoPlayer',
                    name: 'VideoPlayer',
                    meta: {
                      title: 'router.videoPlayer'
                    }
                  },
                  {
                    path: 'avatars',
                    component: 'views/Components/Avatars',
                    name: 'Avatars',
                    meta: {
                      title: 'router.avatars'
                    }
                  },
                  {
                    path: 'i-agree',
                    component: 'views/Components/IAgree',
                    name: 'IAgree',
                    meta: {
                      title: 'router.iAgree'
                    }
                  },
                  {
                    path: 'tree',
                    component: 'views/Components/Tree',
                    name: 'Tree',
                    meta: {
                      title: 'router.tree'
                    }
                  }
                ]
              },
              {
                path: '/function',
                component: '#',
                redirect: '/function/multipleTabs',
                name: 'Function',
                meta: {
                  title: 'router.function',
                  icon: 'vi-ri:function-fill',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'multipleTabs',
                    component: 'views/Function/MultipleTabs',
                    name: 'MultipleTabs',
                    meta: {
                      title: 'router.multipleTabs'
                    }
                  },
                  {
                    path: 'multiple-tabs-demo/:id',
                    component: 'views/Function/MultipleTabsDemo',
                    name: 'MultipleTabsDemo',
                    meta: {
                      hidden: true,
                      title: 'router.details',
                      canTo: true
                    }
                  },
                  {
                    path: 'request',
                    component: 'views/Function/Request',
                    name: 'Request',
                    meta: {
                      title: 'router.request'
                    }
                  },
                  {
                    path: 'test',
                    component: 'views/Function/Test',
                    name: 'Test',
                    meta: {
                      title: 'router.permission',
                      permission: ['add', 'edit', 'delete']
                    }
                  }
                ]
              },
              {
                path: '/hooks',
                component: '#',
                redirect: '/hooks/useWatermark',
                name: 'Hooks',
                meta: {
                  title: 'hooks',
                  icon: 'vi-ic:outline-webhook',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'useWatermark',
                    component: 'views/hooks/useWatermark',
                    name: 'UseWatermark',
                    meta: {
                      title: 'useWatermark'
                    }
                  },
                  {
                    path: 'useTagsView',
                    component: 'views/hooks/useTagsView',
                    name: 'UseTagsView',
                    meta: {
                      title: 'useTagsView'
                    }
                  },
                  {
                    path: 'useValidator',
                    component: 'views/hooks/useValidator',
                    name: 'UseValidator',
                    meta: {
                      title: 'useValidator'
                    }
                  },
                  {
                    path: 'useCrudSchemas',
                    component: 'views/hooks/useCrudSchemas',
                    name: 'UseCrudSchemas',
                    meta: {
                      title: 'useCrudSchemas'
                    }
                  },
                  {
                    path: 'useClipboard',
                    component: 'views/hooks/useClipboard',
                    name: 'UseClipboard',
                    meta: {
                      title: 'useClipboard'
                    }
                  },
                  {
                    path: 'useNetwork',
                    component: 'views/hooks/useNetwork',
                    name: 'UseNetwork',
                    meta: {
                      title: 'useNetwork'
                    }
                  }
                ]
              },
              {
                path: '/level',
                component: '#',
                redirect: '/level/menu1/menu1-1/menu1-1-1',
                name: 'Level',
                meta: {
                  title: 'router.level',
                  icon: 'vi-carbon:skill-level-advanced'
                },
                children: [
                  {
                    path: 'menu1',
                    name: 'Menu1',
                    component: '##',
                    redirect: '/level/menu1/menu1-1/menu1-1-1',
                    meta: {
                      title: 'router.menu1'
                    },
                    children: [
                      {
                        path: 'menu1-1',
                        name: 'Menu11',
                        component: '##',
                        redirect: '/level/menu1/menu1-1/menu1-1-1',
                        meta: {
                          title: 'router.menu11',
                          alwaysShow: true
                        },
                        children: [
                          {
                            path: 'menu1-1-1',
                            name: 'Menu111',
                            component: 'views/Level/Menu111',
                            meta: {
                              title: 'router.menu111'
                            }
                          }
                        ]
                      },
                      {
                        path: 'menu1-2',
                        name: 'Menu12',
                        component: 'views/Level/Menu12',
                        meta: {
                          title: 'router.menu12'
                        }
                      }
                    ]
                  },
                  {
                    path: 'menu2',
                    name: 'Menu2Demo',
                    component: 'views/Level/Menu2',
                    meta: {
                      title: 'router.menu2'
                    }
                  }
                ]
              },
              {
                path: '/example',
                component: '#',
                redirect: '/example/example-dialog',
                name: 'Example',
                meta: {
                  title: 'router.example',
                  icon: 'vi-ep:management',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'example-dialog',
                    component: 'views/Example/Dialog/ExampleDialog',
                    name: 'ExampleDialog',
                    meta: {
                      title: 'router.exampleDialog'
                    }
                  },
                  {
                    path: 'example-page',
                    component: 'views/Example/Page/ExamplePage',
                    name: 'ExamplePage',
                    meta: {
                      title: 'router.examplePage'
                    }
                  },
                  {
                    path: 'example-add',
                    component: 'views/Example/Page/ExampleAdd',
                    name: 'ExampleAdd',
                    meta: {
                      title: 'router.exampleAdd',
                      noTagsView: true,
                      noCache: true,
                      hidden: true,
                      showMainRoute: true,
                      activeMenu: '/example/example-page'
                    }
                  },
                  {
                    path: 'example-edit',
                    component: 'views/Example/Page/ExampleEdit',
                    name: 'ExampleEdit',
                    meta: {
                      title: 'router.exampleEdit',
                      noTagsView: true,
                      noCache: true,
                      hidden: true,
                      showMainRoute: true,
                      activeMenu: '/example/example-page'
                    }
                  },
                  {
                    path: 'example-detail',
                    component: 'views/Example/Page/ExampleDetail',
                    name: 'ExampleDetail',
                    meta: {
                      title: 'router.exampleDetail',
                      noTagsView: true,
                      noCache: true,
                      hidden: true,
                      showMainRoute: true,
                      activeMenu: '/example/example-page'
                    }
                  }
                ]
              },
              {
                path: '/error',
                component: '#',
                redirect: '/error/404',
                name: 'Error',
                meta: {
                  title: 'router.errorPage',
                  icon: 'vi-ci:error',
                  alwaysShow: true
                },
                children: [
                  {
                    path: '404-demo',
                    component: 'views/Error/404',
                    name: '404Demo',
                    meta: {
                      title: '404'
                    }
                  },
                  {
                    path: '403-demo',
                    component: 'views/Error/403',
                    name: '403Demo',
                    meta: {
                      title: '403'
                    }
                  },
                  {
                    path: '500-demo',
                    component: 'views/Error/500',
                    name: '500Demo',
                    meta: {
                      title: '500'
                    }
                  }
                ]
              },
              {
                path: '/authorization',
                component: '#',
                redirect: '/authorization/user',
                name: 'Authorization',
                meta: {
                  title: 'router.authorization',
                  icon: 'vi-eos-icons:role-binding',
                  alwaysShow: true
                },
                children: [
                  {
                    path: 'department',
                    component: 'views/Authorization/Department/Department',
                    name: 'Department',
                    meta: {
                      title: 'router.department'
                    }
                  },
                  {
                    path: 'user',
                    component: 'views/Authorization/User/User',
                    name: 'User',
                    meta: {
                      title: 'router.user'
                    }
                  },
                  {
                    path: 'menu',
                    component: 'views/Authorization/Menu/Menu',
                    name: 'Menu',
                    meta: {
                      title: 'router.menuManagement'
                    }
                  },
                  {
                    path: 'role',
                    component: 'views/Authorization/Role/Role',
                    name: 'Role',
                    meta: {
                      title: 'router.role'
                    }
                  }
                ]
              }
            ]

            // const treeList = infoRes.data.treeList
            const treeList = [
              {
                name: '系统管理',
                path: '/system',
                icon: 'vi-ep:tools',
                component: '#',
                child: [
                  {
                    name: '部门管理',
                    path: 'dept',
                    icon: 'vi-ep:tickets',
                    component: 'views/System/Dept/Index'
                  },
                  {
                    name: '部门用户',
                    path: 'deptUser',
                    icon: 'vi-ep:user-filled',
                    component: 'views/System/DeptUser/Index'
                  },
                  {
                    name: '菜单管理',
                    path: 'menu',
                    icon: 'vi-ep:setting',
                    component: 'views/System/Menu/Index'
                  }
                ]
              }
            ]

            // 获取用户的菜单
            treeList.forEach((val) => {
              routers.push(transferRouter(val))
            })

            userStore.setRoleRouters(routers)
            appStore.getDynamicRouter && appStore.getServerDynamicRouter
              ? await permissionStore.generateRoutes('server', routers).catch(() => {})
              : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})

            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          } else {
            await permissionStore.generateRoutes('static').catch(() => {})
            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          }
        }
      } finally {
        loading.value = false
      }
    }
  })
}

/**
 * 把后端返回的菜单对象转换成前端组件需要的对象
 * @param row 菜单对象
 */
const transferRouter = (row: MenuObj, redirect: string = ''): AppCustomRouteRecordRaw => {
  const children: AppCustomRouteRecordRaw[] = []
  const child = row.child
  if (child && child.length) {
    for (const item of child) {
      children.push(transferRouter(item))
    }
  }
  return {
    path: row.path,
    name: row.name,
    component: row.component,
    redirect: redirect,
    meta: {
      title: row.name,
      icon: row.icon
    },
    children: children
  }
}

// 获取角色信息
// const getRole = async () => {
//   const formData = await getFormData<UserType>()
//   const params = {
//     roleName: formData.username
//   }
//   const res =
//     appStore.getDynamicRouter && appStore.getServerDynamicRouter
//       ? await getAdminRoleApi(params)
//       : await getTestRoleApi(params)
//   if (res) {
//     const routers = res.data || []
//     userStore.setRoleRouters(routers)
//     appStore.getDynamicRouter && appStore.getServerDynamicRouter
//       ? await permissionStore.generateRoutes('server', routers).catch(() => {})
//       : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})

//     permissionStore.getAddRouters.forEach((route) => {
//       addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
//     })
//     permissionStore.setIsAddRouters(true)
//     push({ path: redirect.value || permissionStore.addRouters[0].path })
//   }
// }

// 去注册页面
const toRegister = () => {
  emit('to-register')
}
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"
  />
</template>
